<?php

namespace Modules\Develop\Http\Controllers;

use Catch\Base\CatchController;
use Illuminate\Http\Request;
use Modules\Develop\Models\SchemaFiles;
use Modules\Develop\Models\Schemas;
use Modules\Develop\Support\SchemaColumns;

/**
 * @group 开发模块
 *
 * @subgroup 数据库表管理
 * @subgroupDescription CatchAdmin 数据库表管理
 */
class SchemaController extends CatchController
{
    public function __construct(
        protected Schemas $schemas
    ) {
    }

    /**
     * 数据表列表
     *
     * @return mixed
     */
    public function index()
    {
        return $this->schemas->getList();
    }

    /**
     * 新增表
     *
     *
     * @param Request $request
     * @return bool
     * @throws \Exception
     */
    public function store(Request $request)
    {
        return $this->schemas->storeBy($request->all());
    }

    /**
     * 查询表数据
     *
     * @urlParam id int required 表ID
     *
     * @param $id
     * @param SchemaColumns $schemaColumns
     * @return mixed
     */
    public function show($id, SchemaColumns $schemaColumns): mixed
    {
        $schema = $this->schemas->show($id)->toArray();

        $schema['columns'] = $schemaColumns->parse($schema['columns']);

        return $schema;
    }

    /**
     * 删除表
     *
     * @urlParam id int required 表ID
     *
     * @param $id
     * @return bool|null
     */
    public function destroy($id)
    {
        return $this->schemas->deleteBy($id);
    }

    /**
     * 文件列表
     *
     * @urlParam id int required 表ID
     *
     * @param $id
     * @param SchemaFiles $schemaFiles
     * @param Request $request
     * @return bool|null
     */
    public function files($id, SchemaFiles $schemaFiles, Request $request)
    {
        if ($request->isMethod('PUT')) {
            return $schemaFiles->where('schema_id', $id)->update($request->all());
        }

        return $schemaFiles->where('schema_id', $id)->first([
            'controller_file', 'model_file', 'request_file', 'table_file', 'form_file',
            'controller_path', 'model_path', 'request_path', 'table_path', 'form_path',
        ]);
    }
}
